package com.darker.common.rabbit.config;

import com.darker.common.rabbit.constant.MqConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class MQConfig {

    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }
    @Bean
    public DirectExchange errorMessageExchange(){
        return new DirectExchange(MqConst.ERROR_EXCHANGE);
    }
    @Bean
    public Queue errorQueue(){
        return new Queue(MqConst.ERROR_QUEUE);
    }
    @Bean
    public Binding errorBinding(){
        return BindingBuilder.bind(errorQueue()).to(errorMessageExchange()).with(MqConst.ERROR_KEY);
    }
    /**
     * description: 订单超时交换机
     * @param :
     * @return: DirectExchange<br>
     * date: 2022/12/12 16:32<br>
     * author: Darker<br>
     * version: 1.0
     */
    @Bean
    public DirectExchange orderOutExchange(){
        return new DirectExchange(MqConst.ORDER_TTL_EXCHANGE);
    }
    @Bean
    public Queue orderOutQueue(){
        return QueueBuilder.durable(MqConst.ORDER_TTL_QUEUE)
                .ttl((1000*60)*30)
//                .ttl((1000*60)*15)
                .deadLetterExchange(MqConst.ORDER_DEAD_EXCHANGE)
                .deadLetterRoutingKey(MqConst.ORDER_DEAD_KEY)
                .build();
    }
    @Bean
    public Binding orderOutBinding(){
        return BindingBuilder.bind(orderOutQueue()).to(orderOutExchange())
                .with(MqConst.ORDER_TTL_KEY);
    }

    /**
     * description: 消息发送失败发送到指定交换机处理
     * @param rabbitTemplate:
     * @return: MessageRecoverer<br>
     * date: 2022/12/12 15:28<br>
     * author: Darker<br>
     * version: 1.0
     */
    @Bean
    public MessageRecoverer messageRecoverer(RabbitTemplate rabbitTemplate){
        return new RepublishMessageRecoverer(rabbitTemplate,MqConst.ERROR_EXCHANGE,MqConst.ERROR_KEY);
    }




}
